package com.easyexcel.demo.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @author zhaoxh
 * @version : CourseRowReadListener.java, v 0.1 2025/6/16 zhaoxh Exp $
 */
@Getter
@Slf4j
public class CourseRowReadListener implements ReadListener<Map<Integer, String>> {

    private final Map<Integer, String> resultData = new TreeMap<>();
    private int valueCount = 1; // 用于记录值的顺序

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        ReadRowHolder readRowHolder = context.readRowHolder();
        int row = readRowHolder.getRowIndex();
        if (row != 1) {
            return;
        }

        if (data != null && !data.isEmpty()) {
            List<String> cellDataList = new ArrayList<>(data.values());
            if (cellDataList.size() >= 6) {
                TreeMap<Integer, String> sortedMap = new TreeMap<>();
                int number = 1;
                for (int i = 5; i < Math.min(cellDataList.size(), 5 + 100 * 2); i++) {
                    String cellValue = cellDataList.get(i);

                    if ((i - 5) % 2 == 0){
                        log.info("第{}个课程的值是 {}", valueCount, cellValue);
                        valueCount++;
                    }


                    if (StringUtils.isNotEmpty(cellValue)) {
                        sortedMap.put(i, cellValue);
                    }
                }
                resultData.putAll(sortedMap);
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成");
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        log.error("解析异常:", exception);
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            Integer rowIndex = excelDataConvertException.getRowIndex();
            Integer columnIndex = excelDataConvertException.getColumnIndex();
            String cellData = excelDataConvertException.getCellData().getStringValue();
            log.error("第{}行，第{}列，单元格值[{}]，解析异常:{}", rowIndex, columnIndex, cellData, excelDataConvertException.getMessage());
        } else {
            throw new RuntimeException("Excel解析异常: " + exception.getMessage());
        }
    }
}